package com.llsydn.handler.handler;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.llsydn.hello.R;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author lilinshen
 * @title 测试Handler的使用
 * @description 请填写相关描述
 * @date 2018/9/27 10:24
 */
public class HandlerTestActivity extends AppCompatActivity {

    private EditText et_handler1_result;
    private ProgressBar pb_handler1_loading;

    //创建Handler成员变量对象, 并重写其handleMessage()
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) { //在主线程中执行
            //在handleMessage()中处理消息
            if (msg.what == 1) {
                String result = (String) msg.obj;
                et_handler1_result.setText(result);
                pb_handler1_loading.setVisibility(View.INVISIBLE);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler_test);

        et_handler1_result = findViewById(R.id.et_handler1_result);
        pb_handler1_loading = findViewById(R.id.pb_handler1_loading);
    }

    /**
     * 使用传统方式发送get请求
     *
     * @param view
     */
    public void getSubmit1(View view) {
        //1.主线程，显示提示视图
        pb_handler1_loading.setVisibility(View.VISIBLE);
        //2.分线程，联网请求，并得到响应数据
        new Thread() {
            public void run() {
                try {
                    String path = "http://www.cecjx.com/portal/index/index.jhtml";
                    String result = requestToString(path);
                    //3.主线程，显示数据
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            et_handler1_result.setText(result);
                            pb_handler1_loading.setVisibility(View.INVISIBLE);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 使用handler方法
     * 1.创建Handler成员变量对象, 并重写其handleMessage()
     * 2.在分/主线程创建Message对象
     * 3.使用handler对象发送Message
     * 4.在handleMessage()中处理消息
     *
     * @param view
     */
    public void getSubmit2(View view) {
        //1.主线程，显示提示视图
        pb_handler1_loading.setVisibility(View.VISIBLE);
        //2.分线程，联网请求，并得到响应数据
        new Thread() {
            public void run() {
                try {
                    String path = "http://www.cecjx.com/portal/index/index.jhtml";
                    String result = requestToString(path);

                    //3.主线程，显示数据（使用handler+message方式）

                    //在分/主线程创建Message对象
                    Message message = Message.obtain();
                    message.what = 1; //标识
                    message.obj = result;
                    //使用handler对象发送Message
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 使用HttpURLConnection发送get请求
     *
     * @param path
     * @return
     */
    public String requestToString(String path) {
        String result = "";
        try {
            //创建URL对象
            URL url = new URL(path);
            //打开连接，得到HttpURLConnection对象
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            //设置请求方式，连接超时，读取数据超时
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(100000);
            connection.setReadTimeout(100000);
            //连接服务器
            connection.connect();
            //发请求，得到响应数据
            int responseCode = connection.getResponseCode();
            if (200 == responseCode) {
                //得到InputStream，并读取成String
                InputStream is = connection.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                result = baos.toString();
                baos.close();
                is.close();
            }
            //关闭连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
